<?php

namespace App\Admin\Controllers\Vocabulary;

use App\Admin\Actions\Category\DataExport;
use App\Admin\Repositories\Vocabulary\Vocabulary;
use App\Models\Vocabulary\Vocabulary as VocabularyModel;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;

class VocabularyController extends AdminController
{
    protected $title = '单元词汇表';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $type = \request()->input('_selector')['type'] ?? 0;

        return Grid::make(new Vocabulary(['category', 'click_learn', 'item']), function (Grid $grid) use ($type) {
            $grid->column('id')->sortable();
            $grid->column('type', '类型')->display(function ($value) {
                return VocabularyModel::$isShowMap[$value];
            });
            $grid->column('category.name', '单元名称');
            $grid->column('click_learn.content', '内容');

            if ($type == VocabularyModel::TYPE_AUDITION_LOOK_SPELL_WORD) {
                $grid->column('click_learn.word_blanks', '单词填空')->display(function ($value) {
                    if (strlen($value) === strlen($this->click_learn->content)) {
                        return '<span style="color: #67C23A">' . $value . '</span>';
                    }
                    return '<span style="color: #F56C6C">' . $value . '</span>';
                });
            }

            $grid->column('click_learn.translation', '翻译');
            $grid->column('click_learn.audio_url', '音频');

            if ($type == VocabularyModel::TYPE_AUDITION_WORD || $type == VocabularyModel::TYPE_SELECT_WORD_BLANKS) {
                $grid->column('sentence', '练习题句子');
                $grid->column('item.audio_url', '提示音频');
            }

            $grid->selector(function (Grid\Tools\Selector $selector) {
                $selector->select('category.parent.id', '年级', Vocabulary::categoryList());
                $selector->select('type', '类型', VocabularyModel::$isShowMap);
            });
            $grid->tools(new DataExport('导出数据', '/VocabularyExport'));

            $grid->filter(function (Grid\Filter $filter) {
                $filter->panel();
                $filter->equal('id')->width(2);
                $filter->equal('type', '类型')->select(VocabularyModel::$isShowMap)->width(2);
                $filter->like('category.name', '单元名称')->width(2);
                $filter->like('click_learn.content', '内容')->width(2);
                $filter->like('click_learn.translation', '翻译')->width(2);
            });
        });
    }
}
